package com.dap.cms.governance.aspect;

import com.alibaba.fastjson.JSON;
import com.dap.cms.governance.common.RequestHolder;
import com.dap.cms.governance.exception.ServiceException;
import com.dap.cms.governance.po.CmsManagerPo;
import com.fesine.commons.enums.ResultEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


/**
 * @description: 类描述
 * @author: tigerlin
 * @createTime:2018/7/31 11:16
 * @update:修改内容
 * @author: tigerlin
 * @updateTime:2018/7/31 11:16
 */
@Aspect
@Component
public class WebLogsAspect {
    private final static Logger logger = LoggerFactory.getLogger(WebLogsAspect.class);
    ThreadLocal<Long> startTime = new ThreadLocal<>();
    @Value("${server.authFlag}")
    private boolean authFlag;

    @Pointcut("execution(public * com.dap.cms.governance.controller.*.*(..))"+
            "&& !execution(public * com.dap.cms.governance.controller.CommonController.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
        //登录验证
        CmsManagerPo user = ((CmsManagerPo) request.getSession().getAttribute("user"));
        if (authFlag && null == user) {
            throw new ServiceException(ResultEnum.UNAUTHORIZED);
        }else {
            logger.info("username {}", user.getUsername());
            RequestHolder.add(user);
            RequestHolder.add(request);
        }
    }
    /**
     * 执行完方法后处理
     */
    @After("webLog()")
    public void doAfter() {
        logger.info("执行完方法后处理");
        logger.info("请求执行时间 : " + (System.currentTimeMillis() - startTime.get())+"ms");
        startTime.remove();
    }

    @AfterReturning(returning = "object", pointcut = "webLog()")
    public void afterReturning(Object object) {
        startTime.remove();
        logger.info("object={}", JSON.toJSONStringWithDateFormat(object,"yyyy-MM-dd HH:mm:ss"));

    }


}
